const express = require('express')

const userModel = require('../modules/index')
const Token = require('../utils/Token')

const router = express.Router()

router.post('/', (req, res) => {
  // 获取请求中所传递的用户名与密码数据
  const { username, password } = req.body
  userModel
    .findOne({
      username,
      password,
    })
    .then(data => {
      if (data) {
        const payload = {
          user: data,
        }
        const token = Token.generate(payload)

        res.json({
          code: 200,
          data: {
            token,
          },
          message: '登录成功！'
        })
      } else {
        res.json({
          code: 400,
          data,
          message: '用户名或密码错误！'
        })
      }
    })
    .catch(err => console.log('err:', err))
})

module.exports = router
